window.Geo = {
  watchProcess: null,

  stopWatchLocation: ->
    if Geo.watchProcess != null
      window.navigator.geolocation.clearWatch( Geo.watchProcess )
      Geo.watchProcess = null

  raiseNotice: (text, type="error") ->
    $("div#notice").html('<div class="' + type + '">' + text + '</div>').slideDown( ->
      $("#notice_close").fadeIn("fast")
    )

  hideNotice: ->
    $("#notice_close").fadeOut("fast", ->
      $("#notice").slideUp()
    )

  normalizeYqlResponse: (response) ->
    if response.error
      Geo.didNotGetLocation( { code:0 } )
      return false
    position = {
      coords: {
        latitude: response.place.centroid.latitude,
        longitude: response.place.centroid.longitude
      }
    }
    Geo.gotLocation(position)

  gotLocation: (e) ->
    Position.setPositionFromEvent(e)

  didNotGetLocation: (e) ->
    switch(e.code)
      when 1 then Geo.raiseNotice('Debes permitir que nuestra aplicación utilice tu GPS.')
      when 2 then Geo.raiseNotice('Estoy teniendo problemas al encontrar tu posición actual.', 'notice')
      when 3 then Geo.raiseNotice('Se agotó el tiempo de espera de solicitud de posición.')
      else alert('Se produjo un error desconocido.')

  init: ->
    # Listener on close notice:
    $("#notice_close").live "click", Geo.hideNotice

    # Fix notice:
    $("#notice").hide()

    if Modernizr.geolocation
      # sometimes, watchposition is not called automatically on login, so, ask for position first time:
      window.navigator.geolocation.getCurrentPosition( Geo.gotLocation, Geo.didNotGetLocation )
      Geo.watchProcess = window.navigator.geolocation.watchPosition( Geo.gotLocation, Geo.didNotGetLocation )
    else
      yqlgeo.get('visitor', Geo.normalizeYqlResponse);

    Map.init()
}

window.Position = {
  accuracy: null,
  altitude: null,
  latitude: null,
  longitude: null,
  altitudeAccuracy: null,
  heading: null,
  speed: null,
  timestamp: null,
  setPositionFromEvent: (e) ->
    Position.accuracy = e.coords.accuracy
    Position.altitude = e.coords.altitude
    Position.latitude = e.coords.latitude
    Position.longitude = e.coords.longitude
    Position.altitudeAccuracy = e.coords.altitudeAccuracy
    Position.heading = e.coords.heading
    Position.speed = e.coords.speed
    Position.timestamp = e.timestamp
    Map.do_panToActualPosition()
    obj = {
      type: "position",
      position: Position
    }
    # console.log obj
    Websocket.sendObject( obj )
}